<template>
    <el-card>
        <div slot="header">
            所有通知
            <el-button type="primary"
                       size="small"
                       v-if="$store.state.user.level.id <=2"
                       @click="$router.push('/new_notify')">发新通知
            </el-button>
        </div>
        <el-table
                :data="list"
                :stripe="true"
                @row-click="read">
            <el-table-column label="来自" width="80" prop="from.username"/>
            <el-table-column label="标题" prop="title"/>
            <el-table-column label="发表时间" prop="created_at"/>
        </el-table>
        <br>
        <el-pagination
                background
                layout="prev, pager, next"
                :page-size="$store.state.pageSize"
                @current-change="fetch"
                :current-page.sync="page"
                :total="total" class="inline-block">
        </el-pagination>
    </el-card>
</template>

<script>
    export default {
        data() {
            return {
                page: 0,
                total: 0,
                list: [],
            };
        },
        methods: {
            fetch() {
                this.$http.get('/api/notify', {params: {page: this.page}}).then(res => {
                    const data = res.data;
                    data.list.forEach(item => {
                        item.created_at = moment(item.created_at).calendar();
                    });
                    this.page = data.page;
                    this.total = data.total;
                    this.list = data.list;
                });
            },
            read(row, e, column) {
                if (column.type === 'selection') return;
                this.$http.get('/api/notify/' + row.id).then(res => {
                    const data = res.data;
                    this.$alert(data.content, row.title, {confirmButtonText: '确定'});
                }).catch(err => {
                    this.$message.error(err.response.data);
                });
            },
        },
        mounted() {
            this.fetch();
        }
    }
</script>

<style scoped>
    .unread {
        font-weight: bold;
        color: red;
    }
</style>